package cn.miao.photoprinter.activity;

import java.io.File;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.CheckBox;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import cn.miao.photoprinter.R;
import cn.miao.photoprinter.adapter.MyImageAdapter;
import cn.miao.photoprinter.database.DatabaseHelper;
import cn.miao.photoprinter.entity.PhotoCheckItem;
import cn.miao.photoprinter.util.MMAlert;
import cn.miao.photoprinter.util.ToastUtil;
import cn.miao.photoprinter.util.Util;
import dev.dworks.libs.astickyheader.SimpleSectionedGridAdapter;
import dev.dworks.libs.astickyheader.SimpleSectionedGridAdapter.Section;

public class FavouritesActivity extends CacheActivity {

	private GridView photoGridView;
	private ArrayList<Section> sections = new ArrayList<Section>();
	private MyImageAdapter adapter;
	private TextView tv_noimg, iv_info;
	private ImageView iv_select;
	private static Handler handler;

	private String[] mHeaderNames = {};
	private Integer[] mHeaderPositions = {};

	private static final int LOADOK = 10001;
	private static final int LOADFAIL = 10002;
	
	private final int SHOPPINGORDER = 20002;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_favphoto);
		handler = new MyHandler(this);
		Util.initImageLoader(this);
		initMainView();
		initControls();
		startRefreshPhotos();
	}

	private void startRefreshPhotos() {
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					Thread.sleep(300);
					loadImage();
				} catch (Exception e) {
				}
			}
		}).start();
	}

	private void initControls() {
		photoGridView = (GridView) findViewById(R.id.gv_img);
		adapter = new MyImageAdapter(this);
		// loadImage();
		for (int i = 0; i < mHeaderPositions.length; i++) {
			sections.add(new Section(mHeaderPositions[i], mHeaderNames[i]));
		}
		SimpleSectionedGridAdapter simpleSectionedGridAdapter = new SimpleSectionedGridAdapter(
				this, adapter, R.layout.grid_item_header, R.id.header_layout,
				R.id.header);

		simpleSectionedGridAdapter.setGridView(photoGridView);
		simpleSectionedGridAdapter
				.setSections(sections.toArray(new Section[0]));
		photoGridView.setAdapter(simpleSectionedGridAdapter);
		photoGridView.setOnItemClickListener(new OnItemClickListener() {
			@SuppressLint("NewApi")
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {

				SimpleSectionedGridAdapter simpleAdapter = (SimpleSectionedGridAdapter) parent
						.getAdapter();
				int realPosition = simpleAdapter
						.sectionedPositionToPosition(position);
				Intent intent = new Intent(FavouritesActivity.this,
						ImageActivity.class);
				intent.putExtra("path", adapter.getItem(realPosition).getPath());
				// startActivity(intent);
				CheckBox checkBox = (CheckBox) view.findViewById(R.id.ck_item);
				if (checkBox.isChecked()) {
					checkBox.setChecked(false);
					adapter.getItem(realPosition).setCheck(false);
				} else {
					checkBox.setChecked(true);
					adapter.getItem(realPosition).setCheck(true);
				}
			}
		});
		photoGridView.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> parent, View view,
					int position, long id) {
				SimpleSectionedGridAdapter simpleAdapter = (SimpleSectionedGridAdapter) parent
						.getAdapter();
				final int realPosition = simpleAdapter
						.sectionedPositionToPosition(position);
				// ToastUtil.showTips(FavouritesActivity.this, R.drawable.tips_error, realPosition  + "," + position);
				MMAlert.showAlert(FavouritesActivity.this, getString(R.string.select_menu),
						FavouritesActivity.this.getResources().getStringArray(R.array.select_opts),
						null, new MMAlert.OnAlertSelectId(){

					@Override
					public void onClick(int whichButton) {						
						switch(whichButton){
						case 0: {
							Intent intent = new Intent(FavouritesActivity.this,
									PhotoViewActivity.class);
							intent.putExtra("imagepath", adapter.getItem(realPosition).getPath());
							startActivity(intent);
							break;
						}
						case 2: {
							Intent share = new Intent(Intent.ACTION_SEND); // 启动分享发送的属性
							File file = new File(adapter.getItem(realPosition).getPath());
							share.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file)); 
							share.setType("image/jpeg");
							startActivity(Intent.createChooser(share, "选择分享"));// 目标应用选择对话框的标题
							break;
						}
						default:
							break;
						}
					}
				});
				return true;
			}
		});
	}

	private void refreshPhotos() {
		if (sections.size() > 0) {
			sections.clear();
		}
		for (int i = 0; i < mHeaderPositions.length; i++) {
			sections.add(new Section(mHeaderPositions[i], mHeaderNames[i]));
		}
		SimpleSectionedGridAdapter simpleSectionedGridAdapter = new SimpleSectionedGridAdapter(
				this, adapter, R.layout.grid_item_header, R.id.header_layout,
				R.id.header);

		simpleSectionedGridAdapter.setGridView(photoGridView);
		simpleSectionedGridAdapter
				.setSections(sections.toArray(new Section[0]));
		photoGridView.setAdapter(simpleSectionedGridAdapter);
	}

	int galleryCnt = 0;


	private void initMainView() {
		photoGridView = (GridView) findViewById(R.id.gv_img);
		tv_noimg = (TextView) findViewById(R.id.iv_noimg);
		iv_info = (TextView) findViewById(R.id.iv_info);
		iv_select = (ImageView) findViewById(R.id.iv_select);
		iv_select.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				String selected = adapter.getCheckedItems();
				if (selected.length() > 0) {
					Intent intent = new Intent(FavouritesActivity.this,
							ImageActivity.class);
					intent.putExtra("path", selected);
					// startActivityForResult(intent, SHOPPINGORDER);
					startActivity(intent);
				} else {
					ToastUtil.showTips(FavouritesActivity.this,
							R.drawable.tips_error, "您好像没有选择要打印的照片");
				}
			}
		});
	}

	Dialog dlg;

	@Override
	public void onPause() {
		super.onPause();
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	private String getCheckedItems(GridView gridView) {
		String rtStr = "";
		for (int i = 0; i < gridView.getChildCount(); i++) {
			CheckBox checkBox = (CheckBox) gridView.getChildAt(i).findViewById(
					R.id.ck_item);
			if (null != checkBox && checkBox.isChecked()) {
				TextView path = (TextView) gridView.getChildAt(i).findViewById(
						R.id.tv_path);
				rtStr += "," + path.getText().toString();
			}
		}
		return rtStr.length() > 1 ? rtStr.substring(1) : "";
	}

	private void loadImage() {
		DatabaseHelper dbHelper = new DatabaseHelper(FavouritesActivity.this);
		ArrayList<PhotoCheckItem> photos = (ArrayList<PhotoCheckItem>) dbHelper.queryFavPhoto();
		Map<String, Integer> sections = dbHelper.queryFavPhotoSection();
		if (photos.size() > 0) {
			Iterator<String> iterator = sections.keySet().iterator();
			mHeaderNames = new String[sections.keySet().size()];
			mHeaderPositions = new Integer[sections.keySet().size()];
			int i = 0, previousValue = 0;
			while (iterator.hasNext()) {
				String key = (String) iterator.next();
				mHeaderNames[i] = key;
				if (0 == i) {
					mHeaderPositions[i] = 0;
					previousValue = sections.get(key);
				} else {
					mHeaderPositions[i] = mHeaderPositions[i - 1]
							+ previousValue;
					previousValue = sections.get(key);
				}
				i++;
			}
			Message message = new Message();
			message.obj = photos;
			message.what = LOADOK;
			handler.sendMessage(message);
		} else {
			handler.sendEmptyMessage(LOADFAIL);
		}
	}

	static class MyHandler extends Handler {

		WeakReference<FavouritesActivity> context;

		public MyHandler(FavouritesActivity context) {
			this.context = new WeakReference<FavouritesActivity>(context);
		}

		@SuppressWarnings("unchecked")
		@Override
		public void handleMessage(Message msg) {
			FavouritesActivity activity = context.get();
			switch (msg.what) {
			case LOADOK:
				ArrayList<PhotoCheckItem> photos = (ArrayList<PhotoCheckItem>) msg.obj;
				activity.tv_noimg.setVisibility(View.GONE);
				activity.iv_info.setVisibility(View.GONE);
				activity.adapter.addAll(photos);
				activity.refreshPhotos();
				activity.tv_noimg.setVisibility(View.GONE);
				break;
			case LOADFAIL:
				activity.tv_noimg.setVisibility(View.VISIBLE);
				activity.iv_info.setVisibility(View.GONE);
				break;
			}
			super.handleMessage(msg);
		}
	}
}
